package ccgl.com.action;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import ccgl.com.util.GsonPrint;

public class FileUploadAction extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String uploadDir = "upload";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8"); // 防止中文乱码
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);

		try {
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					System.out.println("表单参数名：" + item.getFieldName()
							+ ",表单参数值：" + item.getString("UTF-8"));
				} else {
					if (item.getName() != null && !item.getName().equals("")) {
						System.out.println("上传文件的大小：" + item.getSize());
						System.out.println("文件的类型：" + item.getContentType());
						System.out.println("上传文件的名称：" + item.getName());
						// item.get
						String filePath = servletContext.getRealPath("/")
								+ File.separatorChar + uploadDir
								+ File.separatorChar
								+ getWebUser(request).getId()
								+ File.separatorChar;
						File file = new File(filePath);
						if (!file.exists()) {
							file.mkdirs();
						}
						file = new File(filePath + item.getName());
						item.write(file);
					} else {
						GsonPrint.printData("没有选择文件", response);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			GsonPrint.printData("上传文件失败", response);
		}
		GsonPrint.printData("上传成功", response);

	}
}
